package com.yihu.wlyy.service.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.yihu.wlyy.entity.SMS;
import com.yihu.wlyy.repository.SMSDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;

@Component
@Transactional(rollbackFor = Exception.class)
public class SMSService extends BaseService {

	@Autowired
	public SMSDao smsDao;

	/**
	 * 发送短信验证码接口
	 * @param mobile 手机号
	 * @param type 消息类型:1微信端注册，2微信端找回密码，3医生端找回密码，4患者登录，5医生登录
	 * @return
	 * @throws Exception 
	 */
	public String send(String mobile, String ip, int type) throws Exception {
		// 生成6位随机验证码
		String captcha = String.valueOf(Math.random()).substring(2, 8);
		// 默认为123456
		// captcha = "123456";
		// 同一ip一天不允许超过10条短信
		String today = DateUtil.getStringDateShort();
		Date begin = DateUtil.strToDate(today + " 00:00:00", DateUtil.YYYY_MM_DD_HH_MM_SS);
		Date end = DateUtil.strToDate(today + " 23:59:59", DateUtil.YYYY_MM_DD_HH_MM_SS);
		// int count = smsDao.countByIp(ip, begin, end);
		// if (count >= SystemConf.MAX_SMS_IP) {
		// return "当前IP：[" + ip + "]今天最多发送" + SystemConf.MAX_SMS_IP + "条短信！";
		// }
		// 一天的短信数不允许超过10条
		int count = smsDao.countByMobile(mobile, begin, end);
		if (count >= SystemConf.MAX_SMS_MOBILE) {
			return "当前手机号：[" + mobile + "]今天最多发送" + SystemConf.MAX_SMS_MOBILE + "条短信！";
		}
		// 两分钟之内不允许重复发送
		PageRequest pageRequest = new PageRequest(0, 1, new Sort(Direction.DESC, "id"));
		Page<SMS> page = smsDao.findByMobileType(mobile, type, pageRequest);
		if (page != null) {
			for (SMS sms : page) {
				if (sms == null) {
					continue;
				}
				// 计算间隔时间
				Date temp = DateUtil.getNextMin(sms.getCzrq(), SystemConf.SMS_INTERVAL);
				long leftTime = (temp.getTime() - System.currentTimeMillis()) / 1000;
				if (leftTime > 0) {
					return "发送短信验证码间隔时间为：" + SystemConf.SMS_INTERVAL + "分钟，还剩" + leftTime + "秒";
				}
			}
		}
		// 保存验证码
		SMS sms = new SMS();
		// 1微信端注册，2微信端找回密码，3医生端找回密码，4患者登录，5医生登录
		if (type == 1) {
			// 患者注册
			sms.setContent("您的注册验证码为：" + captcha);
		} else if (type == 2 || type == 3) {
			// 找回密码
			sms.setContent("您的找回密码验证码为：" + captcha);
		} else if (type == 4 || type == 5) {
			// 登录
			sms.setContent("您的登录验证码为：" + captcha);
		} else {
			// 其他验证码
			sms.setContent("验证码：" + captcha);
		}
		sms.setCaptcha(captcha);
		Date date = new Date();
		// 延后5分钟
		sms.setDeadline(DateUtil.getNextMin(date, 5));
		sms.setCzrq(date);
		sms.setMobile(mobile);
		sms.setIp(ip);
		sms.setType(type);
		sms.setStatus(1);
		// 调用总部发送信息的接口
		String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(sms.getContent(), mobile), "GBK");
		JSONObject json = toJson(result);
		if (json == null) {
			// 发送失败
			throw new Exception("短信发送失败！");
		} else if (json.getInt("result") != 0) {
			return json.getString("description");
		} else {
			//发送成功，保存到数据库
			smsDao.save(sms);
		}
		return "ok";
	}

	/**
	 * 验证码校验
	 * @param mobile 手机号
	 * @param type type 消息类型:1微信端注册，2微信端找回密码，3医生端找回密码，4患者登录，5医生登录
	 * @param captcha 验证码
	 * @return -1验证码过期，-1验证码错误，0验证码无效，1验证通过
	 */
	public int check(String mobile, int type, String captcha) {
		// 根据手机号和验证码查询对应的短信信息
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, 1, sort);
		Page<SMS> page = smsDao.findByCaptcha(mobile, captcha, type, pageRequest);
		SMS sms = null;
		for (SMS temp : page) {
			if (temp != null) {
				sms = temp;
				break;
			}
		}
		// 验证码校验
		if (sms == null) {
			// 验证码错误
			return -1;
		} else if (type != sms.getType()) {
			// 验证码无效，也视为错误
			return -1;
		} else if (sms.getDeadline().before(new Date())) {
			// 验证码过期
			return -2;
		}
		return 1;
	}

	public static List<NameValuePair> buildSmsParams(String content, String mobile) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("SpCode", SystemConf.getInstance().getSmsCode()));
		params.add(new BasicNameValuePair("LoginName", SystemConf.getInstance().getSmsName()));
		params.add(new BasicNameValuePair("Password", SystemConf.getInstance().getSmsPassword()));
		params.add(new BasicNameValuePair("MessageContent", content));
		params.add(new BasicNameValuePair("UserNumber", mobile));
		params.add(new BasicNameValuePair("SerialNumber", String.valueOf(System.currentTimeMillis())));
		params.add(new BasicNameValuePair("ScheduleTime", ""));
		params.add(new BasicNameValuePair("f", "1"));
		return params;
	}

	public static JSONObject toJson(String result) {
		JSONObject json = new JSONObject();
		try {
			String[] temps = result.split("&");
			for (String temp : temps) {
				if (temp.split("=").length != 2) {
					continue;
				}
				String key = temp.split("=")[0];
				String value = temp.split("=")[1];
				json.put(key, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	public static void main(String[] args) {

		// JSONObject params = new JSONObject();
		// params.put("SpCode", SystemConf.SMS_SP_CODE);
		// params.put("LoginName", SystemConf.SMS_LOGIN_NAME);
		// params.put("Password", SystemConf.SMS_PASSWORD);
		// params.put("MessageContent", "您的找回密码验证码为：123456");
		// params.put("UserNumber", "18559687019");
		// params.put("SerialNumber", "");
		// params.put("ScheduleTime", "");
		// params.put("f", 1);
		//
		// // String result = HttpUtil.sendPost(SystemConf.SMS_URL, params.toString(), "GBK");
		// String result = HttpClientUtil.post(SystemConf.SMS_URL, buildSmsParams("您的找回密码验证码为：123456", "18559687019"), "GBK");
		// JSONObject json = toJson(result);
		// System.out.println(json.toString());
		// System.out.println(json.getInt("result"));
		// if (json.getInt("result") != 0) {
		// System.out.println("短信发送失败！");
		// }

		System.out.println(toJson("result=0&description=发送短信成功&taskid=22624861237&faillist=&task_id=22624861237"));
	}

}
